package _02_链表;

/**
 * https://leetcode-cn.com/problems/add-two-numbers/
 *
 * @Author: haogege
 * @Date: 2021/8/26
 */
public class _2_两数相加 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        ListNode newHead = new ListNode(0);
        ListNode tail = newHead;
        boolean isCarry = false;
        while (l1 != null || l2 != null) {
            int first = 0;
            int second = 0;
            if (l1 != null) {
                first = l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                second = l2.val;
                l2 = l2.next;
            }
            int sum = first + second + (isCarry ? 1 : 0);
            isCarry = sum > 9;
            tail = tail.next = new ListNode(isCarry ? sum - 10 : sum);
        }
        if (isCarry) {
            tail.next = new ListNode(1);
        }
        return newHead.next;
    }

}
